package com.sprocomm.agingtest.mic;

import com.sprocomm.agingtest.BaseActivity;
import com.sprocomm.agingtest.Config;
import com.sprocomm.agingtest.R;
import com.sprocomm.agingtest.Tools;
import com.sprocomm.agingtest.views.CDTTextView;

import android.media.MediaRecorder;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;

public class MicTestActivity extends BaseActivity {
    private CDTTextView mCDTTextView;
    private Button mBtnStart;
    private MediaRecorder mMediaRecorder;
    private TextView mTextShowPath;
    private boolean isRecord = false;
    private String recordFilePath = "/AgingTest/Temp/Record";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mic_test);
        mCDTTextView = (CDTTextView) findViewById(R.id.cdt_timer);
        mBtnStart = (Button) findViewById(R.id.btn_start);
        mTextShowPath = (TextView) findViewById(R.id.tv_file_path);
        mTextShowPath.setText("Save path:"+getFilePath());
    }

    private void startMediaRecorder() {
        if (mMediaRecorder == null){
            mMediaRecorder = new MediaRecorder();
        }
        try {
            mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
            mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
            mMediaRecorder.setOutputFile(File.createTempFile("Record", ".mp3", getFilePath()).getAbsolutePath());
            mMediaRecorder.prepare();
            mMediaRecorder.start();
        }catch (IOException e){
            e.printStackTrace();
            Toast.makeText(this,"Record failed",Toast.LENGTH_LONG).show();
            if (mCDTTextView != null){
                mCDTTextView.setTimerCancle();
                mCDTTextView.setText("Record failed");
            }
            isRecord = false;
        }
        isRecord = true;
    }

    private File getFilePath() {
        File root = Environment.getExternalStorageDirectory();
        File file = new File(root.getAbsolutePath() + recordFilePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file;
    }

    /**
     * 清空录制的sound
     * 如果超过10个文件就删除最新的一个文件
     */
    private void cleanVedio() {
        File file = getFilePath();
        if (file == null) {
            return;
        }
        File[] files = file.listFiles();
        if (files.length <= 10) return;
        File delFile = files[0];
        for (int i = 0; i < files.length; i++) {
            if (delFile.lastModified() > files[i].lastModified()){
                delFile = files[i];
            }
        }
        if (delFile != null) delFile.delete();
    }

    private void releaseMediaRecorder(){
        if (mMediaRecorder != null){
            mMediaRecorder.stop();
            mMediaRecorder.reset();
            mMediaRecorder.release();
            mMediaRecorder = null;
        }
        isRecord = false;
    }

    public void start(View view){
        Tools.logE("click start");
        mBtnStart.setEnabled(false);
        mCountDownTimer.start();
        mCDTTextView.setCountDownTimer(Config.MIC_TEST_TIME,1000);
        mCDTTextView.setTimerStart();
    }

    private CountDownTimer mCountDownTimer = new CountDownTimer(Config.MIC_TEST_TIME,Config.MIC_CHANGE_TIME) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (isRecord){
                releaseMediaRecorder();
                cleanVedio();
            }
            startMediaRecorder();
        }

        @Override
        public void onFinish() {
            releaseMediaRecorder();
            setPassBtnEnable(true);
            mBtnStart.setEnabled(true);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaRecorder();
        if (mCountDownTimer != null){
            mCountDownTimer.cancel();
        }
    }

}
